// colorui/year-month-picker/year-month-picker.js
Component({
  properties: {
    // 是否显示选择器
    show: {
      type: Boolean,
      value: false,
      observer: function(newVal) {
        console.log('选择器显示状态:', newVal);
      }
    },
    // 默认选中的年月段，格式为"YYYY-MM-1"或"YYYY-MM-2"
    defaultValue: {
      type: String,
      value: ''
    },
    // 开始年份
    startYear: {
      type: Number,
      value: 2000
    },
    // 结束年份
    endYear: {
      type: Number,
      value: new Date().getFullYear() + 10
    }
  },

  data: {
    years: [],
    months: Array.from({length: 12}, (_, i) => i + 1),
    periods: ['上旬', '下旬'],
    pickerValue: [0, 0, 0],
    selectedYear: 0,
    selectedMonth: 0,
    selectedPeriod: 1 // 1:上旬, 2:下旬
  },

  observers: {
    'show': function(show) {
      console.log(show)
      if (show) {
        this.initData();
      }
    }
  },

  methods: {
    initData() {
      const { startYear, endYear } = this.properties;
      const years = [];
      
      for (let i = startYear; i <= endYear; i++) {
        years.push(i);
      }
      
      this.setData({ years }, () => {
        this.setDefaultValue();
      });
    },
    
    setDefaultValue() {
      const { defaultValue, startYear } = this.properties;
      let year, month, period;
      
      if (defaultValue) {
        [year, month, period] = defaultValue.split('-').map(Number);
      } else {
        const date = new Date();
        year = date.getFullYear();
        month = date.getMonth() + 1;
        period = date.getDate() <= 15 ? 1 : 2;
      }
      
      const yearIndex = year - startYear;
      const monthIndex = month - 1;
      const periodIndex = period - 1;
      
      this.setData({
        pickerValue: [yearIndex, monthIndex, periodIndex],
        selectedYear: year,
        selectedMonth: month,
        selectedPeriod: period
      });
    },
    
    bindChange(e) {
      const { value } = e.detail;
      const { years, months, periods } = this.data;
      const { startYear } = this.properties;
      
      const year = years[value[0]];
      const month = months[value[1]];
      const period = value[2] + 1; // 转换为1或2
      
      this.setData({
        selectedYear: year,
        selectedMonth: month,
        selectedPeriod: period
      });
    },
    
    onConfirm() {
      const { selectedYear, selectedMonth, selectedPeriod } = this.data;
      const month = selectedMonth < 10 ? `0${selectedMonth}` : selectedMonth;
      
      this.triggerEvent('confirm', {
        year: selectedYear,
        month: selectedMonth,
        period: selectedPeriod,
        value: `${selectedYear}-${month}-${selectedPeriod}`,
        periodText: selectedPeriod === 1 ? '上旬' : '下旬'
      });
      
      this.onClose();
    },
    
    onClose() {
      this.triggerEvent('close');
    },
    
    preventTouchMove() {
      return;
    }
  }
});